from sqlalchemy import Column, BigInteger, String, Text, JSON, Integer, TIMESTAMP, ForeignKey
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.db.session import Base


class Post(Base):
    """图文内容表"""
    __tablename__ = "posts"
    
    id = Column(BigInteger, primary_key=True, autoincrement=True, comment="内容ID")
    title = Column(String(255), nullable=False, comment="帖子标题")
    content = Column(Text, nullable=False, comment="帖子正文")
    images = Column(JSON, nullable=True, comment="图片URL列表，存储在对象存储中的路径")
    tags = Column(String(255), nullable=True, comment="标签，以逗号分隔")
    status = Column(Integer, nullable=False, default=0, comment="状态: 0-草稿, 1-待发布, 2-已发布, 3-发布失败")
    author_id = Column(BigInteger, nullable=True, comment="创建者ID")
    error_message = Column(Text, nullable=True, comment="发布失败时的错误信息")
    created_at = Column(TIMESTAMP, nullable=False, server_default=func.current_timestamp(), comment="创建时间")
    updated_at = Column(
        TIMESTAMP, 
        nullable=False, 
        server_default=func.current_timestamp(),
        onupdate=func.current_timestamp(),
        comment="更新时间"
    )
    
    # 关联关系
    publish_job = relationship("PublishJob", back_populates="post", uselist=False)


class PublishJob(Base):
    """发布任务表"""
    __tablename__ = "publish_jobs"
    
    id = Column(BigInteger, primary_key=True, autoincrement=True, comment="任务ID")
    post_id = Column(BigInteger, ForeignKey("posts.id"), nullable=False, unique=True, comment="关联的图文内容ID")
    xxl_job_id = Column(Integer, nullable=True, comment="在XXL-Job调度中心的任务ID")
    job_cron = Column(String(100), nullable=False, comment="任务执行的CRON表达式")
    job_desc = Column(String(255), nullable=False, comment="任务描述")
    status = Column(Integer, nullable=False, default=0, comment="任务状态: 0-待启动, 1-运行中, 2-已停止, 3-已完成")
    created_at = Column(TIMESTAMP, nullable=False, server_default=func.current_timestamp(), comment="创建时间")
    updated_at = Column(
        TIMESTAMP, 
        nullable=False, 
        server_default=func.current_timestamp(),
        onupdate=func.current_timestamp(),
        comment="更新时间"
    )
    
    # 关联关系
    post = relationship("Post", back_populates="publish_job")